package gui.tools;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import tools.RotateTool;

public class RotateToolSetup extends JPanel {

	private RotateTool mRotateTool;
	
	private JTextField mTxtX;
	
	private JTextField mTxtY;
	
	private JTextField mTxtAngle;
	
	private JButton mBtnOk;
	
	public RotateToolSetup(RotateTool tool) {
		mRotateTool = tool;
		init();
		setEnabled(false);
	}
	
	protected void init() {
		
		GridBagLayout layout = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		
		setLayout(layout);
		
		c.gridx = 0;
		c.gridy = 0;
		add(new JLabel("x:"), c);
		
		mTxtX = new JTextField(4);
		c.gridx = 1;
		add(mTxtX, c);
		
		c.gridx = 0;
		c.gridy = 1;
		add(new JLabel("y:"), c);
		
		mTxtY = new JTextField(4);
		c.gridx = 1;
		add(mTxtY, c);
		
		c.gridx = 0;
		c.gridy = 2;
		add(new JLabel("\u03B8:"), c);
		
		mTxtAngle = new JTextField(4);
		c.gridx = 1;
		add(mTxtAngle, c);
		
		mBtnOk = new JButton("Ok");
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 2;
		c.anchor = GridBagConstraints.CENTER;
		add(mBtnOk, c);
		
		mBtnOk.addActionListener(mListener);
		mTxtX.getDocument().addDocumentListener(mDocListener);
		mTxtY.getDocument().addDocumentListener(mDocListener);
		
		reset();
	}
	
	public void setEnabled(boolean b) {
		mTxtX.setEnabled(b);
		mTxtY.setEnabled(b);
		mTxtAngle.setEnabled(b);
		mBtnOk.setEnabled(b);
	}
	
	public void reset() {
		mTxtX.setText("0");
		mTxtY.setText("0");
		mTxtAngle.setText("0");
	}
	
	private DocumentListener mDocListener = new DocumentListener() {
		
		@Override
		public void removeUpdate(DocumentEvent e) {
			changedUpdate(e);
		}
		
		@Override
		public void insertUpdate(DocumentEvent e) {
			changedUpdate(e);
		}
		
		@Override
		public void changedUpdate(DocumentEvent e) {
			
			int x = 0;
			int y = 0;
			
			try {
				x = Integer.parseInt(mTxtX.getText());
				y = Integer.parseInt(mTxtY.getText());
			}
			catch(NumberFormatException nfe) {
			}
			
			mRotateTool.updateRotationCenter(x, y);
		}
	};
	
	private ActionListener mListener = new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			int x = Integer.parseInt(mTxtX.getText());
			int y = Integer.parseInt(mTxtY.getText());
			int teta = Integer.parseInt(mTxtAngle.getText());
			
			reset();
			mRotateTool.rotate(x, y, teta);
		}
	};
	
}
